﻿using GN.Pay.Core.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp.Dependency;
using RabbitMQ.GNClient;
using RabbitMQ.GNClient.Events;
using GN.Pay.Core.Services;
using GN.Pay.Core.Exceptions;
using System.Transactions;
using GN.Pay.Core.Services.Impl;

namespace GN.Pay.Core.Tasks.Queue.Impl
{
    /// <summary>
    /// 客户端Http通知消费队列
    /// </summary>
    class ClientHttpNotifyConsumerQueue : AConsumerQueue<TradeNotify>, IClientHttpNotifyConsumerQueue
    {
        /// <summary>
        /// 
        /// </summary>
        public IPayNotifyService PayNotifyService { get; set; }

        public ClientHttpNotifyConsumerQueue(IIocManager iocManager)
            : base(QueueType.ClientHttpNotify, iocManager)
        {
            this.PayNotifyService = NullPayNotifyService.Instance;
        }

        /// <summary>
        /// 
        /// </summary>
        protected override ushort MaxPrefetchCount
        {
            get
            {
                return 10;
            }
        }

        /// <summary>
        /// 最大通知次数
        /// </summary>
        public int MaxNotifyCount
        {
            get
            {
                return 5000;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="eventConsumer"></param>
        /// <param name="data"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        protected override async Task Consumer(IEventingConsumer eventConsumer, TradeNotify data, DeliverEventArgs e)
        {
            await Task.Run(() =>
            {
                int count = data.Count;
                count++;

                //TODO:通知次数判断
                if (count >= 1000)
                {
                    eventConsumer.Channel.Ack(e.DeliveryTag);
                    return;
                }

                bool isRestNotify;
                try
                {
                    isRestNotify = !RunNotify(data, count);
                }
                catch (Exception err)
                {
                    data.Status = 2;
                    data.NotifyMsg = err.Message;
                    Logger.Error("通知异常:", err);
                    isRestNotify = true;
                }
                try
                {
                    var queue = IocManager.Resolve<IQueueManager>();
                    if (isRestNotify)
                    {
                        this.DelayConsumer(eventConsumer, data, e, DelayTimeSpan(count));
                    }
                    else
                    {
                        PayNotifyService.NotifySuccess(data);
                        eventConsumer.Channel.Ack(e.DeliveryTag);
                    }
                }
                catch (Exception err)
                {
                    Logger.Error("回调队列异常:", err);
                    this.DelayConsumer(eventConsumer, data, e, new TimeSpan(0, 0, 10));
                }
            });
        }

        private TimeSpan DelayTimeSpan(int count)
        {
            if (count < 5)
            {
                return new TimeSpan(0, 0, 10);
            }
            if (count < 10)
            {
                return new TimeSpan(0, 0, 20);
            }
            return new TimeSpan(0, 0, 30);
        }

        /// <summary>
        /// 运行通知
        /// </summary>
        /// <param name="notify">通知</param>
        /// <returns></returns>
        private bool RunNotify(TradeNotify notify, int count)
        {
            notify.LastNotifyTime = DateTime.Now;
            notify.NotifyMsg = "";
            notify.Count = count;
            notify.Status = 1;
            var service = IocManager.Resolve<ITradeNotifyService>();
            try
            {
                var options = CreateUpdateUnitOfWorkOptions();
                using (var uow = UnitOfWorkManager.Begin(options))
                {
                    var result = service.ClientNotify(notify);
                    if (!result.Item1 && notify.Count % 10 == 0)
                    {
                        notify.NotifyMsg = result.Item2;
                        notify.Status = 2;
                        service.UpdateNotify(notify);
                    }
                    uow.Complete();
                    return result.Item1;
                }
            }
            //以下两种错误均不可能再次成功
            catch (PaySystemException err)
            {
                Logger.Error("通知异常:", err);
                notify.NotifyMsg = err.Message;
                notify.Status = 2;
                Update(notify);
                return true;
            }
            catch (PaySignException err)
            {
                Logger.Error("通知异常:", err);
                notify.NotifyMsg = err.Message;
                notify.Status = 2;
                Update(notify);
                return true;
            }
            catch (Exception err)
            {
                Logger.Error("通知异常:", err);
                notify.NotifyMsg = err.Message;
                notify.Status = 2;
                if (notify.Count % 5 == 0)
                {
                    notify.NotifyMsg = err.Message;
                    notify.Status = 2;
                    Update(notify);
                }
                return false;
            }
        }


        private void Update(TradeNotify notify)
        {
            var service = IocManager.Resolve<ITradeNotifyService>();
            this.UpdateUnitOfWork(() =>
            {
                service.UpdateNotify(notify);
            });
        }
    }
}
